package com.freesun.shop.controller;

import com.freesun.shop.entity.User;
import com.freesun.shop.entity.UserAddr;
import com.freesun.shop.param.OrderParm;
import com.freesun.shop.service.BasketService;
import com.freesun.shop.service.OrderService;
import com.freesun.shop.service.TransportService;
import com.freesun.shop.service.UserAddrService;
import com.freesun.shop.vo.OrderResultVo;
import com.freesun.shop.vo.ShopCartItem;
import com.freesun.shop.vo.ShopCartItemDiscount;
import com.freesun.shop.vo.ShopCartOrder;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private UserAddrService userAddrService;

    @Reference(check = false)
    private BasketService basketService;

    @Reference(check = false)
    private OrderService orderServie;
    @Reference(check = false)
    private TransportService transportService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostConstruct
    public void setRedis() {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }



    private static final String CONFIRM_ORDER_RESULT_PREFIX = "confim_order_result:";
    @ApiOperation("用户确认订单")
    @PostMapping("p/order/confirm")
    public ResponseEntity<OrderResultVo> confimOrder(@RequestBody OrderParm orderParm) {
        OrderResultVo orderResultVo = new OrderResultVo();
        List<ShopCartOrder> shopCartOrders = new ArrayList<ShopCartOrder>();
        ShopCartOrder shopCartOrder = new ShopCartOrder();
        shopCartOrder.setShopCartItemDiscounts(getShopCartItemDiscounts(orderParm.getBasketIds()));

        List<ShopCartItem> shopCartItems = shopCartOrder.getShopCartItemDiscounts().get(0).getShopCartItems();
        // 计算购物车里面商品的运费
        //运费和收货地址，以及用户买的商品，以及金额相关
        // 总的商品金额  不包含运费
        BigDecimal totalPay = basketService.getTotalPay(orderParm.getBasketIds());
        BigDecimal transFree = transportService.calFee(orderParm.getAddrId(), shopCartItems, totalPay);
        shopCartOrder.setTransfee(transFree);
        // 计算购物车里面商品的优惠
        shopCartOrder.setShopReduce(new BigDecimal("0.00"));
        shopCartOrders.add(shopCartOrder);
        orderResultVo.setShopCartOrders(shopCartOrders);
        Integer totalCount = 0; // 总的商品数据
        List<ShopCartItem> cartItems = orderResultVo.getShopCartOrders().get(0).getShopCartItemDiscounts().get(0).getShopCartItems();
        for (ShopCartItem shopCartItem : cartItems) {
            totalCount += shopCartItem.getProdCount();
        }
        orderResultVo.setTotalCount(totalCount);

        orderResultVo.setTotal(totalPay);
        //  实际支付的商品金额 总的金额- 优化金额 + 运费
        ShopCartOrder shopCartOrderFee = orderResultVo.getShopCartOrders().get(0);
        orderResultVo.setActualTotal(new BigDecimal(totalPay.doubleValue() + shopCartOrderFee.getTransfee().doubleValue()));
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        UserAddr userAddr = userAddrService.getUserDefaultAddr(user.getUserId());
        orderResultVo.setUserAddr(userAddr);


        redisTemplate.opsForValue().set(CONFIRM_ORDER_RESULT_PREFIX + user.getUserId(), orderResultVo, Duration.ofMinutes(15));
        return ResponseEntity.ok(orderResultVo);
    }

    /**
     * 购物车的条目对象
     *
     * @return
     */
    private List<ShopCartItemDiscount> getShopCartItemDiscounts(List<Long> basketIds) {
        //查询购物车的条目
        List<ShopCartItem> shopCartItems = basketService.findByBasketIds(basketIds);

        ShopCartItemDiscount shopCartItemDiscount = new ShopCartItemDiscount();
        shopCartItemDiscount.setShopCartItems(shopCartItems);
        List<ShopCartItemDiscount> shopCartItemDiscounts = new ArrayList<ShopCartItemDiscount>();
        shopCartItemDiscounts.add(shopCartItemDiscount);
        return shopCartItemDiscounts;
    }

    @PostMapping("/p/order/submit")
    public ResponseEntity<String> submitOrder() {
        //需要远程调用Orderservice
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        OrderResultVo orderResultVo = (OrderResultVo) redisTemplate.opsForValue().get(CONFIRM_ORDER_RESULT_PREFIX + user.getUserId());
        String payUrl = orderServie.createPreOrder(orderResultVo);
        return ResponseEntity.ok(payUrl);
    }
}
